/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable array-callback-return */
/* eslint-disable eqeqeq */
/* eslint-disable array-callback-return */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-param-reassign */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, Modal, message, DatePicker } from 'antd';
import queryString from 'query-string';
import Link from 'umi/link';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import Customer from '../../components/Customer';
import DictCode from '../../components/DictCode';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
@connect(({ accusearrch, loading, publicdata }) => ({
  data: accusearrch.data,
  dataInfo: accusearrch.detail || {},
  loading: loading.models.accusearrch,
  accusearrch,
  dictCode: publicdata.dictCode,
  expandForm: accusearrch.expandForm,
  formFieldsValue: accusearrch.formFieldsValue,
  monthvalue: accusearrch.monthvalue,
}))
@Form.create()
class Accusearrch extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      // eslint-disable-next-line react/no-unused-state
      modalVisible: false,
      selectedRows: [],
      suppId: '',
      areaIdList: [],
      // payWayList: [],
      mode: ['month', 'month'],
      scroll: {
        x: 1900,
        y: 400,
      },
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    this.columns = [
      {
        title: '员工姓名',
        dataIndex: 'empName',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        // render: (text, record) => <Link to={`/socaccmanage/accusearrch/detail?empId=${record.empId}`}>{text}</Link>,
        render: (text, record) => (
          <Link to={`${tempUrl}/detail?empId=${record.empId}`}>{text}</Link>
        ),
        fixed: 'left',
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        width: 200,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        fixed: 'left',
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '签约方',
        dataIndex: 'ordSndrName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '公积金个人账号',
        dataIndex: 'empIndvAccoNo',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => (val && val) || '--',
      },
      {
        title: '缴费方式',
        dataIndex: 'payType',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          const { dictCode } = this.props;
          const yesor = record.payType;
          let name;
          if (yesor) {
            // eslint-disable-next-line no-unused-expressions
            dictCode &&
              dictCode.PAY_FEES_WAY &&
              dictCode.PAY_FEES_WAY.map(c => {
                // eslint-disable-next-line eqeqeq
                if (c.itemCode == yesor) {
                  name = c.itemName;
                }
              });
          }
          return <span>{name}</span>;
        },
      },
      {
        title: '执行地区',
        dataIndex: 'declAreaName',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '企业基数',
        dataIndex: 'unitBase_2',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '个人基数',
        dataIndex: 'empBase_2',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '企业缴费比例(%)',
        dataIndex: 'unitProp_2',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '个人缴费比例(%)',
        dataIndex: 'empProp_2',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '企业缴费',
        dataIndex: 'unitAmo',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '个人缴费',
        dataIndex: 'empAmo',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '账户余额',
        dataIndex: 'accoAmo',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '业务年月',
        dataIndex: 'busiYm',
        width: 100,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
    ];
  }

  componentDidMount() {
    // this.accusearrchSearch();
    this.getDict();
    const { location, dispatch } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const { queryParam } = location;
    if (isMenuLink === 'true') {
      this.resetAndGeLlist(location);
    } else if (isMenuLink === 'false') {
      if (queryParam) {
        dispatch({
          type: 'accusearrch/updateModalData',
          payload: {
            formFieldsValue: queryParam,
            expandForm: true,
          },
        });
        const _ = this;
        this.accusearrchSearch(_, queryParam);
      } else {
        this.accusearrchSearch();
      }
    } else {
      this.accusearrchSearch();
    }
  }

  getDict = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['PAY_FEES_WAY'],
    });
  };

  detial = record => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/detail?empId=${record.empId}`);
  };

  // 查询列表
  accusearrchSearch = (_, queryParam) => {
    // if (e) e.preventDefault();
    const {
      dispatch,
      form,
      data: {
        pagination: { pageSize },
      },
    } = this.props;
    const { monthvalue } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (monthvalue.length !== 0) {
        // eslint-disable-next-line no-param-reassign
        fieldsValue.dateArr = monthvalue;
      }

      fieldsValue = queryParam || fieldsValue;

      dispatch({
        type: 'accusearrch/updateModalData',
        payload: {
          formFieldsValue: fieldsValue,
        },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'empName' || key === 'certNo') {
          fieldsValue[key] = (fieldsValue[key] && fieldsValue[key].trim()) || null;
        }
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
      });
      const pageArg = { currentPage: 1, pageSize: pageSize };
      const values = {
        ...formFieldsValue,
        pageArg,
        custId: fieldsValue.custId || null,
        payType: fieldsValue.payType || null,

        startBusiYm: monthvalue.length !== 0 ? monthvalue[0].format('YYYYMM') : null,
        endBusiYm: monthvalue.length !== 0 ? monthvalue[1].format('YYYYMM') : null,
      };
      this.setState({ formValues: values });
      dispatch({
        type: 'accusearrch/fetchList',
        payload: values,
      });
    });
  };

  // 重置
  accusearrchFormReset = () => {
    // const { form } = this.props;
    // form.resetFields();
    // this.setState({
    //   monthvalue: [],
    // });
    // form.validateFields((err, fieldsValue) => {
    //   if (err) return;
    //   const formFieldsValue = {};
    //   Object.keys(fieldsValue).forEach(key => {
    //     formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
    //   });
    //   const pageArg = { currentPage: 1, pageSizes: 10 };
    //   const values = {
    //     ...formFieldsValue,
    //     pageArg,
    //     custId: null,
    //     payType: null,
    //     startBusiYm: null,
    //     endBusiYm: null,
    //   };
    //   this.setState({ formValues: values });
    // });
    const { form, dispatch } = this.props;
    dispatch({
      type: 'accusearrch/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ startBusiYm: null });
    this.dateOnchange();
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'accusearrch/updateModalData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  accusearrchSelectRows = (rows, selectedRowKeys) => {
    this.setState({ selectedRows: rows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  accusearrchStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const pageArg = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    const params = {
      ...formValues,
      ...filters,
      pageArg,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'accusearrch/fetchList',
      payload: params,
    });
  };

  // 更改状态:废弃
  updateStatus = suppProtId => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: `你确定要废弃此协议吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'accusearrch/updateStatus',
          payload: { suppProtId },
          callback: response => {
            if (response.success) {
              this.accusearrchSearch();
              message.success('废弃成功！');
            } else {
              message.warning('废弃失败!');
            }
          },
        });
      },
    });
  };

  // 模态框显隐
  accusearrchModalVisible = flag => {
    this.setState({
      // eslint-disable-next-line react/no-unused-state
      modalVisible: !!flag,
    });
  };

  // 获取供应商名称
  getSuppName = value => {
    const { areaIdList } = this.state;
    if (areaIdList.length) {
      this.getProductList(value, areaIdList);
    }
    this.setState({ suppId: value });
  };

  // 获取地区
  getAreaList = value => {
    const { suppId } = this.state;
    if (suppId) {
      this.getProductList(suppId, value);
    }
    this.setState({ areaIdList: value });
  };

  // 获取产品下拉数据
  getProductList = (suppId, areaIdList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accusearrch/fetchProductList',
      payload: { suppId, areaIdList },
    });
  };

  // 添加
  add = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accusearrch/getDetail',
      payload: {},
    });
    this.accusearrchModalVisible(true);
  };

  accusearrchPanelChange = (value, mode) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accusearrch/updateModalData',
      payload: { monthvalue: value },
    });

    this.setState({
      mode: [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]],
    });
  };

  dateOnchange = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accusearrch/updateModalData',
      payload: { monthvalue: [] },
    });
    this.setState({
      mode: ['month', 'month'],
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    dispatch({
      type: 'accusearrch/updateModalData',
      payload: { expandForm: false },
    });
    await this.accusearrchFormReset();
    await this.accusearrchSearch();
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="员工姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.accusearrchSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.accusearrchFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      monthvalue,
      // accusearrch,
    } = this.props;
    const { mode } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="员工姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(<Customer attr />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="缴费方式" {...this.tableSearchLayout}>
              {getFieldDecorator('payType', {
                initialValue: formFieldsValue.payType,
              })(<DictCode dictType="PAY_FEES_WAY" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="业务年月" {...this.tableSearchLayout}>
              {getFieldDecorator('startBusiYm', {
                rules: [{ type: 'array', required: false }],
                initialValue: formFieldsValue.startBusiYm,
              })(
                <div>
                  <RangePicker
                    placeholder={['开始缴纳月份', '结束缴纳月份']}
                    format="YYYY-MM"
                    value={monthvalue}
                    mode={mode}
                    onPanelChange={this.accusearrchPanelChange}
                    onChange={this.dateOnchange}
                  />
                </div>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.accusearrchSearch()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.accusearrchFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { data, loading } = this.props;
    const { selectedRows, selectedRowKeys, scroll } = this.state;
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              loading={loading}
              scroll={scroll}
              data={data}
              onSelectRow={this.handleSelectRows}
              columns={this.columns}
              rowKey={record => record.ordYmDetId || null}
              // eslint-disable-next-line react/jsx-no-duplicate-props
              onSelectRow={this.accusearrchSelectRows}
              onChange={this.accusearrchStandardTableChange}
              bordered
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Accusearrch;
